Skip to content

Components

Components are a huge part of React. If you only know one thing about React, you probably know that it is a component-based framework.

What is a component, exactly? Here's how I like to define them: a component is a bundle of markup, styles, and logic that controls everything about a specific part of the user interface.

It's a different mental model when it comes to code organization. Instead of separating our application into markup (written in HTML), styles (written in CSS), and logic (written in JS), we organize our application into components.

There's a lovely graphic that I think illustrates this really well:

A graph showing 3 colored pillars for HTML, CSS, and JS. Another graph shows 3 gradient pillars, mixing the technologies, but organized into components (Button, Datepicker, Modal, etc)

Credit for this wonderful image goes to Cristiano Rastelli.

Mechanisms of reuse

Traditional HTML doesn't really have a way to reuse chunks of markup. Many languages will use partials to achieve this. A partial is a chunk of HTML that can be inserted into another HTML document.

In CSS, the main mechanism we have for reuse is the class. For example, we might create a standard “button” style, under the btn class:

.btn {
padding: 8px 32px;
background: blue;
border: none;
font-size: 1rem;
}

Whenever we want to apply this set of styles to an HTML element, we can pop the btn class onto it.

And for JavaScript, the mechanism of reuse is the function. Maybe we have a function to process data in some way:

function shout(sentence) {
return sentence.toUpperCase() + '!!';
}
shout("we're off to see the wizard")
// -> "WE'RE OFF TO SEE THE WIZARD!!"

With React, components are the main mechanism of reuse. Instead of partials for HTML, classes for CSS, and functions for JavaScript, we create a component that bundles up all 3, and allows us to create a library of high-level reusable UI elements.

This idea is really very powerful. It takes a while to get accustomed to thinking in components, but once you do, you'll never want to work on a project without them.

(Modern React also features hooks, which offers a way to reuse React logic! We'll learn all about them in the modules ahead.)